package com.lkd.handler;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class SupplyTaskHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        log.info("采集到状态数据");
        var supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);

        if(StringUtils.isBlank(supplyContract.getInnerCode()) || CollectionUtils.isEmpty(supplyContract.getSupplyData())){
            log.error("接收自动补货工单消息失败" + jsonMsg);
            return;
        }

        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setAssignorId(0);
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setCreateType(VMSystem.TASK_CREATE_TYPE_AUTO);

        int leastUser = taskService.getLeastUser(supplyContract.getRegionId(), false);
        if(leastUser == 0){
            log.error("获取工单数最少的运营人员失败：" + jsonMsg);
            return;
        }
        taskViewModel.setUserId(leastUser);

        List<TaskDetailsViewModel> details = supplyContract.getSupplyData().stream().map(x -> {
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setSkuName(x.getSkuName());
            taskDetailsViewModel.setSkuId(x.getSkuId());
            taskDetailsViewModel.setSkuImage(x.getSkuImage());
            taskDetailsViewModel.setExpectCapacity(x.getCapacity());
            taskDetailsViewModel.setChannelCode(x.getChannelId());
            return taskDetailsViewModel;
        }).collect(Collectors.toList());
        taskViewModel.setDetails(details);

        taskService.create(taskViewModel);
    }
}